package com.cvmars.jianyou.api.api;

import android.text.TextUtils;

import com.cvmars.jianyou.utils.LogUtils;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class Interceptors {
    private ArrayList<Interceptor> mInterceptors = new ArrayList<>();

    public Interceptors() {


//        //第二个拦截器
//        //添加请求log打印
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

            private StringBuilder mMessage = new StringBuilder();

            @Override
            public void log(String message) {
                if (TextUtils.isEmpty(message))
                    return;
                String s = message.substring(0, 1);
                //如果收到想响应是json才打印
                if ("{".equals(s) || "[".equals(s)) {
                    LogUtils.d( "======" + message);
//                    Logger.i("收到响应"+message);
                }

                // 请求或者响应开始
                if (message.startsWith("--> POST")) {
                    mMessage.setLength(0);
                }
                // 以{}或者[]形式的说明是响应结果的json数据，需要进行格式化
                if ((message.startsWith("{") && message.endsWith("}"))
                        || (message.startsWith("[") && message.endsWith("]"))) {
                    message = JsonUtil.formatJson(JsonUtil.decodeUnicode(message));
                }
                mMessage.append(message.concat("\n"));
                // 响应结束，打印整条日志
                if (message.startsWith("<-- END HTTP")) {
                    LogUtils.d(mMessage.toString());
                }

            }
        });
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        mInterceptors.add(interceptor);

    }


    public ArrayList<Interceptor> getInterceptors() {
        return mInterceptors;
    }
}
